//
//  AppDelegate.m
//  Ufan
//
//  Created by yangqingluo on 15/10/17.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "WWSideslipViewController.h"
#import "Reachability.h"
#import "AppPublic.h"
#import "MainSlideVC.h"
#import "LeftViewController.h"
#import "MainViewController.h"
#import "RightViewController.h"
#import "WelcomeView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiManager.h"

@interface AppDelegate (){
    BOOL hasLogin;
    
    BOOL isReachable;
    Reachability *internetReachability;
}



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [[AppPublic shareInstanceApp] adjustNavBar];
    [WXApi registerApp:@"wx41839dc62aba22b8" withDescription:@"锦食"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appdelegateFunction:)
                                                 name:kAppDelegateFunction
                                               object:nil];
    
    [self loginStateChange:nil];
    
    if (!internetReachability) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        
        internetReachability = [Reachability reachabilityForInternetConnection];
        [internetReachability startNotifier];
        [self updateInterfaceWithReachability:internetReachability];
    }
    
    return YES;
}


#pragma mark-----Notification
- (void)reachabilityChanged:(NSNotification *)note{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}


- (void)updateInterfaceWithReachability:(Reachability *)reachability{
    if (reachability == internetReachability){
        switch ([reachability currentReachabilityStatus]) {
            case NotReachable:{
                isReachable = NO;
                
            }
                break;
            case ReachableViaWiFi:
            case ReachableViaWWAN:{
                isReachable = YES;
                if (hasLogin) {
                    [self doLogin];
                }
            }
                break;
                
            default:
                break;
        }
    }
    
}

#pragma mark - private
//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification{
    QKUserData *userdata = [AppPublic shareInstanceApp].username_password;
    
    if (userdata) {//登陆成功加载主窗口控制器
        hasLogin = YES;
//        [AppPublic shareInstanceApp].mainSlide = [[MainSlideVC alloc]initWithLeftView:[LeftViewController new] andMainView:[[UINavigationController alloc] initWithRootViewController:[MainViewController new]] andRightView:nil andBackgroundImage:[UIImage imageNamed:@"slide_bg"]];
//        
//        self.window.rootViewController = [AppPublic shareInstanceApp].mainSlide;
    }
    else{//登陆失败加载登陆页面控制器
        hasLogin = NO;
        
//        [AppPublic shareInstanceApp].mainSlide = nil;
//        
//        UINavigationController *nav = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"IninialNavVC"];
//        
//        self.window.rootViewController = nav;
    }
    
//    if (isFirstUsing()) {
//        //暂时取消欢迎界面
//        WelcomeView *welcome = [[WelcomeView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//        [self.window.rootViewController.view addSubview:welcome];
//    }
    
//    [AppPublic shareInstanceApp].mainSlide = [[MainSlideVC alloc]initWithLeftView:[LeftViewController new] andMainView:[[UINavigationController alloc] initWithRootViewController:[MainViewController new]] andRightView:nil andBackgroundImage:[UIImage imageNamed:@"slide_bg"]];
    
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[MainViewController new]];

}

-(void)appdelegateFunction:(NSNotification *)notification{
    NSNumber *functionNumber = (NSNumber *)[notification object];
    switch ([functionNumber intValue]) {
        case FUN_LOGIN:{
            [self loginStateChange:nil];
        }
            break;
            
        case FUN_LOGOUT:{
            [[AppPublic shareInstanceApp] clearUserData];
//            [self loginStateChange:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kHttpStateLogoutSuccess object:nil];
        }
            break;
            
        default:
            break;
    }
    
}


- (void)doLogin{
    [QKHttpManager loginWithUsername:[AppPublic shareInstanceApp].username_password.username password:[AppPublic shareInstanceApp].username_password.password completion:^(NSObject *object, NSError *error){
        
    }];
    
}




- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([[NSString stringWithFormat:@"%@",url] hasPrefix:@"wx"]) {
        //微信支付
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    
    //跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
    }];
    
    return YES;
    
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}






- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
